package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Part part = request.getPart("imgFile");
            String fileName= UUID.randomUUID().toString().concat(".jpg");
            String uploadPath=request.getSession().getServletContext().getRealPath("images/");
            File file=new File(uploadPath);
            if(!file.exists()){
                file.mkdir();
                System.out.println("目录创建成功！");
            }
            part.write(uploadPath.concat(fileName));
            request.setAttribute("msg","上传成功！文件名为：".concat(fileName).concat("<br/>保存路径：").concat(uploadPath));
            request.getRequestDispatcher("upload.jsp").forward(request,response);
        } catch (IOException e) {
            e.printStackTrace();
            request.setAttribute("msg","上传失败！错误原因："+e.getMessage());
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }

}
